import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as systemNotificationApi from '@/api/notification'
import NotificationService from '@/utils/notification'

/**
 * 系统通知状态管理
 * 管理系统通知相关的状态
 */
export const useSystemNotificationStore = defineStore('systemNotification', () => {
  // 系统通知列表
  const notifications = ref([])
  // 未读通知数量
  const systemUnreadCount = ref(0)
  
  // 添加系统通知（带去重）
  const addNotificationUnique = (notification) => {
    // 检查通知是否已存在
    const exists = notifications.value.some(msg => msg.notification_id === notification.notification_id)
    
    // 如果通知不存在，则添加到列表开头
    if (!exists) {
      notifications.value.unshift({
        ...notification
      })
      
      // 增加未读计数
      if (!isNotificationRead(notification)) {
        incrementUnreadCount();
      }
    }
  }
  
  // 设置系统通知（替换整个通知列表）
  const setNotifications = (newNotifications) => {
    // 计算未读数量
    const unread = newNotifications.filter(n => !isNotificationRead(n)).length;
    setUnreadCount(unread);
    
    notifications.value = newNotifications.map(notification => ({
      ...notification
    }))
  }
  
  // 检查通知是否已读
  const isNotificationRead = (notification) => {
    // 根据后端逻辑检查已读状态
    if (notification.receive_users) {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo && userInfo.user_id) {
          const userId = userInfo.user_id;
          // 检查该用户是否在receive_users中，并且已读
          return notification.receive_users[userId] && notification.receive_users[userId].read;
        }
      } catch (e) {
        console.error('解析用户信息失败:', e);
      }
    }
    // 默认为未读
    return false;
  }
  
  // 更新未读通知数量
  const setUnreadCount = (count) => {
    systemUnreadCount.value = count
  }
  
  // 增加未读通知数量
  const incrementUnreadCount = () => {
    systemUnreadCount.value++
  }
  
  // 减少未读通知数量
  const decrementUnreadCount = () => {
    if (systemUnreadCount.value > 0) {
      systemUnreadCount.value--
    }
  }
  
  // 清空所有通知数据
  const clearNotifications = () => {
    notifications.value = []
    systemUnreadCount.value = 0
  }
  
  // 处理系统通知接收
  const handleSystemNotificationReceived = (data) => {
    addNotificationUnique(data)
    if (!isNotificationRead(data)) {
      incrementUnreadCount();
    }

    // 触发设备提醒（震动和声音）
    // NotificationService.triggerNotification({
    //   vibrate: true,
    //   sound: true
    // });
    
    // 在App平台上创建系统通知栏消息
    // #ifdef APP-PLUS
    NotificationService.showSystemNotification(data, 'system_notification');
    // #endif
  }
  
  // 处理系统通知已读成功的响应
  const handleSystemNotificationReadSuccess = (notificationId) => {
    try {
      if (notifications.value && Array.isArray(notifications.value)) {
        const notification = notifications.value.find(n => n.notification_id === notificationId)
        if (notification) {
          // 更新通知的已读状态
          if (notification.receive_users) {
            const userInfo = uni.getStorageSync('userInfo');
            if (userInfo && userInfo.user_id) {
              const userId = userInfo.user_id;
              if (!notification.receive_users[userId]) {
                notification.receive_users[userId] = {};
              }
              notification.receive_users[userId].read = true;
            }
          } else {
            notification.is_read = true;
          }
          // 减少未读计数
          decrementUnreadCount()
        }
      }
    } catch (error) {
      console.error('处理系统通知已读状态时出错:', error)
    }
  }

  return {
    // 状态
    notifications,
    systemUnreadCount,

    // 方法
    addNotificationUnique,
    setNotifications,
    setUnreadCount,
    incrementUnreadCount,
    decrementUnreadCount,
    clearNotifications,
    handleSystemNotificationReceived,
    handleSystemNotificationReadSuccess
  }
})